<template>
  <zm-dialog
    :title="pTitle"
    :visible.sync="value"
    append-to-body
    size="small"
    :before-close="dialogClose"
    :close-on-click-modal="false"
  >
    <el-form
      class="el_form"
      :model="form"
      ref="form"
      :rules="Rules"
      label-width="140px"
      label-position="right"
    >
      <!-- <el-form-item label="回款类型：" prop="returnedType">
        <zm-data-radio
          v-model="form.returnedType"
          k1="returnedType"
          label-name="name"
          class="w300"
          @change="returnedTypeChange"
        ></zm-data-radio>
      </el-form-item> -->
      <el-form-item label="回款日期：" prop="returnedTime">
        <el-date-picker
          v-model="form.returnedTime"
          type="date"
          placeholder="选择日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <zm-form-item
        label="归属业务员："
        prop="salesmanId"
        v-if="!loading"
      >
        <!-- v-if="!obj.id || (obj.id && salesmanId.length === 2)" -->
        <el-cascader
          placeholder="归属业务员"
          :props="props"
          v-model="salesmanId"
          :options="accountList"
          clearable
          class="w200"
          @change="salesmanChange"
        ></el-cascader>
      </zm-form-item>
      <el-form-item label="所属部门：" v-if="form.salesmanId">
        {{ apartmentName }}
      </el-form-item>
      <el-form-item label="关联客户：" prop="customerId" v-if="form.salesmanId">
        <zm-data-select
          v-model="form.customerId"
          api="getCustomerList"
          :params="{ accountId: form.salesmanId, type: form.returnedType }"
          placeholder="请选择关联客户"
          class="w300"
          @change="customerChange"
        ></zm-data-select>
      </el-form-item>
      <el-form-item
        label="销售单号："
        prop="saleOrderNo"
        v-if="form.salesmanId && form.customerId && !loading"
      >
        <zm-data-select
          v-model="form.saleOrderNo"
          api="getSaleOrderList"
          :params="{ accountId: form.salesmanId, customerId: form.customerId, type: form.returnedType }"
          placeholder="请选择销售单号"
          class="w300"
          label-name="orderNo"
          value-key="orderNo"
          ref="selectOrderNo"
          @change="getsaleOrderName"
        ></zm-data-select>
      </el-form-item>
      <el-form-item label="销售单名称：" v-if="form.saleOrderNo">
        {{ form.saleName }}
      </el-form-item>
      <el-form-item label="已回款金额：" v-if="form.saleOrderNo">
        {{ form.yetReturnedMoney || 0 }}元
      </el-form-item>
      <el-form-item label="剩余金额：" v-if="form.saleOrderNo">
        {{ form.residue || 0 }}元
      </el-form-item>
      <el-form-item label="审批冻结金额：" v-if="form.saleOrderNo && form.returnedType === '1'">
        {{ form.approvalReturnedMoney || 0 }}元
      </el-form-item>
      <el-form-item
        label="回款金额："
        prop="returnedMoney"
        v-if="form.returnedType === '1'"
      >
        <zm-input
          v-model="form.returnedMoney"
          placeholder="请输入回款金额"
          class="w300"
        />
      </el-form-item>
      <el-form-item
        label="红冲金额："
        prop="balanceAmount"
        v-if="form.returnedType === '2'"
      >
        <zm-input
          v-model="form.balanceAmount"
          placeholder="请输入红冲金额"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="付款单位：" prop="payer">
        <zm-input
          v-model="form.payer"
          placeholder="请输入付款单位"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="交易方式：" prop="exchangeMeans">
        <zm-data-select
          v-model="form.exchangeMeans"
          k1="returnedPayType"
          label-name="name"
          placeholder="交易方式"
          class="w300"
        ></zm-data-select>
      </el-form-item>
      <el-form-item
        label="交易银行："
        prop="dealBank"
        v-if="form.exchangeMeans === '1'"
      >
        <zm-input
          v-model="form.dealBank"
          placeholder="请输入交易银行"
          class="w300"
        />
      </el-form-item>
      <el-form-item
        label="转账方式："
        prop="transferType"
        v-if="form.exchangeMeans === '2'"
      >
        <zm-data-select
          v-model="form.transferType"
          k1="transferType"
          label-name="name"
          placeholder="转账方式"
          class="w300"
        ></zm-data-select>
      </el-form-item>
      <el-form-item label="收款单位：" prop="gathering">
        <zm-data-select
          v-model="form.gathering"
          api="getOrderCompanyList"
          label-name="companyName"
          value-key="companyId"
          placeholder="收款单位"
          class="w300"
        ></zm-data-select>
      </el-form-item>
      <el-form-item label="交易流水号：" prop="transactionNo">
        <zm-input
          v-model="form.transactionNo"
          placeholder="请输入交易流水号"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="回款凭证：">
        <zm-upload class="w300" v-model="form.enclosureName" @on-remove="onFileRemove" :http-request="fileUpload" accept=".rar,.zip,.doc,.docx,.pdf,.png,.jpg,.pptx" :limit="1" :single-file-size="5">
          <zm-button>上传</zm-button>
        </zm-upload>
      </el-form-item>
      <el-form-item label="备注信息：" prop="remark">
        <zm-input
          type="textarea"
          v-model="form.remark"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 3 }"
          :maxlength="500"
          class="w400"
          :disabled="routeNameIsApprove"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button size="small" @click="dialogClose">取消</el-button>
      <el-button size="small" type="primary" @click="submitOrder">
        保存订单
      </el-button>
      <el-button
        size="small"
        type="primary"
        @click="approval"
        v-if="
          (obj.checkStatus === '0' ||
            obj.checkStatus === '2' ||
            obj.checkStatus === '4' ||
            !obj.id) &&
            isApprove === '0'
        "
      >
        提交审批
      </el-button>
    </div>
  </zm-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialogMixin'
import { INVOICE_MAKETYPE } from '../const'
// import { getAccountList } from '@/api/src/public'
import {
  getInfo,
  getSaleOrderInfo,
  update,
  create,
  getAccountList
} from '@/api/src/returnedMoney'
import { submit, checkApprove } from '@/api/src/approve'
import systemAccount from '@/api/src/systemAccount'
import { dft } from '@/utils'
import { getSaleOrderList } from '@/api/src/publicSelect'
import validataRules from '@/utils/validateRule'
import { mapGetters } from 'vuex'
import ZmUpload from '@/components/ZmUpload/components/main'
import uploadApis from '@/api/src/upload'

export default {
  components: {ZmUpload},
  mixins: [dialogMixin],
  props: {
    isApprove: {
      type: String,
      default: '0'
    },
    obj: {
      type: Object,
      default: {}
    },
    id: {
      type: String,
      default: ''
    },
    props: {
      type: Object,
      default () {
        return {
          label: 'name',
          value: 'id',
          children: 'accountData'
        }
      }
    }
  },
  data () {
    return {
      INVOICE_MAKETYPE,
      dft,
      form: {
        returnedType: '1',
        returnedTime: dft('now', 'YYYY-MM-DD'), // 回款日期默认为当前日期，单选单个时间
        salesmanId: '',
        apartmentId: '',
        customerId: '',
        saleOrderNo: '',
        saleName: '',
        yetReturnedMoney: '',
        returnedMoney: '',
        balanceAmount: '',
        residue: '',
        approvalReturnedMoney: '',
        payer: '',
        exchangeMeans: '',
        dealBank: '',
        gathering: '',
        transferType: '',
        transactionNo: '',
        remark: '',
        enclosureUrl: '',
        enclosureName: ''
      },
      apartmentName: '',
      salesmanId: [],
      accountList: [],
      loading: false,
      Rules: {
        returnedTime: {
          required: true,
          message: '选择回款日期',
          trigger: 'change'
        },
        salesmanId: {
          required: true,
          message: '请选择归属业务员',
          trigger: 'blur'
        },
        customerId: {
          required: true,
          message: '请输入关联客户',
          trigger: 'blur'
        },
        saleOrderNo: {
          required: true,
          message: '请输入销售单号',
          trigger: 'blur'
        },
        returnedMoney: [{
          required: true,
          message: '请输入本期回款金额',
          trigger: 'blur'
        }, {
          validator: validataRules.stringNumber,
          trigger: 'blur'
        }],
        balanceAmount: [
          {
            required: true,
            message: '请输入红冲金额',
            trigger: 'blur'
          },
          {
            validator: validataRules.stringNumber,
            trigger: 'blur'
          }
        ],
        exchangeMeans: {
          required: true,
          message: '请选择交易方式',
          trigger: 'change'
        },
        transferType: {
          required: true,
          message: '请选择转账方式',
          trigger: 'change'
        },
        gathering: {
          required: true,
          message: '请输入收款单位',
          trigger: 'blur'
        },
        payer: {
          required: true,
          message: '请输入付款单位',
          trigger: 'blur'
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    routeNameIsApprove () {
      return this.$route.name === 'approvalMgr'
    },
    pTitle () {
      return this.obj.id ? '编辑' : '新增'
    },
    productInfo () {
      return product(this)
    }
  },
  created () {
    this.init()
    if (this.obj.id) {
      this.getInfo()
    }
  },
  methods: {
    async init () {
      this.accountList = await getAccountList()
      if (!this.obj.id) {
        this.$set(this.salesmanId, 0, this.userInfo.departmentId)
        this.$set(this.salesmanId, 1, this.userInfo.userId)
        this.$set(this.form, 'salesmanId', this.userInfo.userId)
        this.getApartmentName(this.userInfo.userId)
      }
    },
    async getInfo () {
      this.loading = true
      const form = await getInfo({
        id: this.obj.id
      })
      this.form = Object.assign({}, this.form, form)
      this.$set(this.salesmanId, 0, this.form.apartmentId)
      this.$set(this.salesmanId, 1, this.form.salesmanId)
      this.getApartmentName(this.form.salesmanId)
    },
    async getApartmentName (val) {
      // 获取业务员的部门
      this.loading = false
      const info = await systemAccount.getInfo({ id: val })
      this.form.apartmentId = info.apartmentId
      this.apartmentName = info.apartmentName
    },
    async salesmanChange (val) {
      this.loading = true
      this.form = Object.assign({}, this.form, {
        apartmentId: '',
        apartmentName: '',
        customerId: '',
        saleOrderNo: '',
        salesmanId: '',
        saleName: '',
        approvalReturnedMoney: '0'
      })

      if (val.length === 0) {
        this.loading = false
        return
      }
      this.$nextTick(() => {
        this.form.salesmanId = this.salesmanId[1]
        this.getApartmentName(val[1])
      })
    },
    customerChange () {
      // 客户切换 销售单要重新渲染
      this.loading = true
      this.form = Object.assign({}, this.form, {
        saleOrderNo: '',
        saleName: '',
        yetReturnedMoney: '',
        residue: '',
        approvalReturnedMoney: '0'
      })
      this.$nextTick(() => {
        this.loading = false
      })
    },
    async getsaleOrderName () {
      // const saleData = await getSaleOrderList({
      //   accountId: this.form.salesmanId,
      //   customerId: this.form.customerId,
      //   type: this.form.returnedType
      // })
      const saleData = this.$refs.selectOrderNo.apiList
      const item = saleData.find(item => {
        return item.orderNo === this.form.saleOrderNo
      })
      this.form.saleName = (item && item.name) || '无匹配数据'
      const _amount = await getSaleOrderInfo({
        saleOrderNo: this.form.saleOrderNo
      })
      this.$set(this.form, 'yetReturnedMoney', _amount.yetReturnedMoney)
      this.$set(this.form, 'residue', _amount.residue)
      this.$set(this.form, 'approvalReturnedMoney', _amount.approvalReturnedMoney)
    },
    returnedTypeChange () {
      // 重新渲染销售单
      this.$set(this.form, 'returnedMoney', '')
      this.$set(this.form, 'balanceAmount', '')
      this.customerChange()
      this.$refs.form.clearValidate()
    },
    async submitOrder () {
      let _valid = false
      this.$refs.form.validate(valid => {
        _valid = valid
      })
      if (!_valid) {
        return
      }

      if (
        this.form.returnedType === '2' &&
        +this.form.balanceAmount + +this.form.residue > 0
      ) {
        this.$message.error('红冲金额输入错误')
        return
      }

      if (
        this.form.returnedType === '1' &&
        +this.form.returnedMoney > +this.form.residue - +this.form.approvalReturnedMoney
      ) {
        this.$confirm(
          '本期回款的金额已超过剩余金额减去冻结金额, 确定提交审批/保存?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.submitOrderFunc()
          })
          .catch(() => {})
      } else {
        this.submitOrderFunc()
      }
    },
    submitOrderFunc () {
      const _api = this.obj.id ? update : create
      _api(this.form).then(r => {
        this.$message.success(`${this.pTitle}成功`)
        this.$emit('after-save')
        this.dialogClose()
      })
    },
    approval () {
      let _valid = false
      this.$refs.form.validate(valid => {
        _valid = valid
      })
      if (!_valid) {
        return
      }

      if (
        this.form.returnedType === '2' &&
        +this.form.balanceAmount + +this.form.residue > 0
      ) {
        this.$message.error('红冲金额输入错误')
        return
      }

      if (
        this.form.returnedType === '1' &&
        +this.form.returnedMoney > +this.form.residue - +this.form.approvalReturnedMoney
      ) {
        this.$confirm(
          '本期回款的金额已超过剩余金额减去冻结金额, 确定提交审批/保存?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.sumbitFunc()
          })
          .catch(() => {})
      } else {
        this.sumbitFunc()
      }
    },
    sumbitFunc () {
      checkApprove({ processType: '7' })
        .then(check => {
          create(this.form).then(async r => {
            const params = {
              processType: '7', // 7->回款录入审批
              linkName: r.returnedNo + r.customerName, // 审批标题
              businessId: r.id // 关联的业务表id
            }
            await submit(params)
            this.$message.success(`${this.pTitle}成功`)
            this.$emit('after-save')
            this.dialogClose()
          })
        })
        .catch(e => {
          console.log(e.content)
        })
    },
    async fileUpload (data) {
      let params = new FormData()
      params.append('fileData', data.file)
      const res = await uploadApis.uploadFile(params)
      this.$set(this.form, 'enclosureUrl', res.url)
      this.$set(this.form, 'enclosureName', res.name)
      return res.url
    },
    onFileRemove () {
      this.form.enclosureUrl = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.el_form::v-deep .el-form-item__error{
  padding:0
}
</style>
